package com.jgp.workflow.controller;

import com.jgp.common.annotation.UIParam;
import com.jgp.common.pojo.LabelValue;
import com.jgp.common.utils.JGPUtil;
import com.jgp.sys.controller.JGPBackController;
import com.jgp.sys.model.Attribute;
import com.jgp.sys.service.AttributeService;
import com.jgp.sys.ui.GridResult;
import com.jgp.sys.ui.Pager;
import com.jgp.sys.ui.Result;
import com.jgp.workflow.exception.WorkflowException;
import com.jgp.workflow.pojo.ViewProcessModel;
import com.jgp.workflow.service.EditorService;
import org.activiti.engine.repository.Model;
import org.apache.batik.transcoder.TranscoderException;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 项目   jgp-cloud-parent
 * 作者   loufei
 * 时间   2018/11/14
 */
@CrossOrigin
@RestController
@RequestMapping("/workflow/editorApiController")
public class EditorApiController extends JGPBackController {
    
    private static final String CATEGORY_KEY = "SYS.WORKFLOW.CATEGORY";
    
    @Autowired
    private EditorService editorService;
    
    @Autowired
    private AttributeService attributeService;
    
    @RequestMapping(value = "/editor/stencilset", method = RequestMethod.GET,
                    produces = "application/json;charset=utf-8")
    public String stencilset() {
        InputStream stream = this.getClass().getClassLoader()
                                 .getResourceAsStream("back/workflow/designer/stencilset.json");
        try {
            return IOUtils.toString(stream, "UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    
    @RequestMapping("/model/{modelId}/json")
    public Map modelJson(@PathVariable("modelId") String modelId) {
        return editorService.queryModelEditor(modelId);
    }
    
    @RequestMapping(value = "/model/{modelId}/save")
    public void modelSave(@PathVariable(
            "modelId") String modelId, String json_xml, String svg_xml, String name, String description, HttpServletRequest request)
            throws WorkflowException, IOException, TranscoderException {
        editorService.saveModelEditor(modelId, json_xml, svg_xml, name, description);
    }
    
    @RequestMapping("/saveModel")
    public Result saveModel(String id, String name, String systemId, String category, String description) throws WorkflowException {
        editorService.saveModel(id, name, systemId, category, description);
        return ajaxRe(true);
    }
    
    @RequestMapping("/queryModelById/{modelId}")
    public Result queryModelById(@PathVariable("modelId") String modelId) throws IOException {
        Model model = editorService.queryModelById(modelId);
        Map<String, Object> metaInfoMap = JGPUtil.jsonToMap(model.getMetaInfo());
        return ajaxReForm("fdata", model)
                .addData("description", metaInfoMap.get("description"));
    }
    
    @RequestMapping("/queryAllModels")
    public Result queryAllModels(@UIParam("pager") Pager pager) throws WorkflowException {
        List<ViewProcessModel> processModels = editorService.queryModels(pager);
        List<GridResult.Category> categories = new ArrayList<>();
        categories.add(new GridResult.Category("发布状态", "deploymentId"));
        categories.add(new GridResult.Category("模型名称", "name"));
        categories.add(new GridResult.Category("流程定义KEY", "key"));
        categories.add(new GridResult.Category("模型描述", "description"));
        categories.add(new GridResult.Category("创建时间", "createTime"));
        categories.add(new GridResult.Category("版本", "version"));
        categories.add(new GridResult.Category("修改时间", "lastUpdateTime"));
        categories.add(new GridResult.Category("修订版本", "revision"));
        return ajaxReGrid("gdata", categories, processModels, pager);
    }
    
    @RequestMapping("/removeModel")
    public Result removeModel(String modelId) {
        editorService.removeModel(modelId);
        return ajaxRe(true);
    }
    
    @RequestMapping("/queryCategory")
    public Result queryCategory(@UIParam("pager") Pager pager) {
        List<Attribute> list = queryWorkFlowCategory();
        List<GridResult.Category> categories = new ArrayList<>();
        categories.add(new GridResult.Category("类型名称", "label"));
        categories.add(new GridResult.Category("类型值", "value"));
        return ajaxReGrid("gdata", categories, list, pager);
    }
    
    @RequestMapping("/dropCategory")
    public Result dropCategory() {
        List<LabelValue> list = attributeService.queryLabelValuesByActiveKey(CATEGORY_KEY);
        return ajaxReData("ldata", list);
    }
    
    @RequestMapping("/saveCategory")
    public Result saveCategory(Attribute category) {
        Attribute group = attributeService.queryListGroup(CATEGORY_KEY);
        if(Objects.isNull(group)){
            group = new Attribute();
            group.setValue(CATEGORY_KEY);
            group.setLabel("流程分类");
            attributeService.saveList(group);
        }
        category.setValue(CATEGORY_KEY+"."+category.getValue().toUpperCase());
        attributeService.saveListItem(category);
        return ajaxRe(true);
    }
    
    private List<Attribute> queryWorkFlowCategory(){
        return attributeService.queryListItem("SYS.WORKFLOW.CATEGORY",null,null,null);
    }
    
}
